import {
  Component, ViewEncapsulation, ChangeDetectionStrategy, Input, ViewChild, Output,
  EventEmitter, AfterContentInit
} from '@angular/core';
import {Subject} from "rxjs/Subject";

@Component({
  selector: 'seed-textarea-form',
  templateUrl: './textarea-form.component.html',
  styleUrls: ['./textarea-form.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class TextareaFormComponent implements AfterContentInit {
  /*输入文字内容*/
  private _text = '';

  /*最大数量*/
  private _maxQuantity: number | string;

  /*宽度*/
  private _width: any;

  /*高度*/
  private _height: any;

  /*只读属性*/
  private _readonly: boolean = false;


  /*text area value*/
  private _value$ = new Subject<string>();

  @Input()
  get width(): any {
    return this._width;
  }

  set width(value: any) {
    this._width = value;
  }

  @Input()
  get height(): any {
    return this._height;
  }

  set height(value: any) {
    this._height = value;
  }

  @Input()
  get maxQuantity(): number | string {
    return this._maxQuantity;
  }

  set maxQuantity(value: number | string) {
    this._maxQuantity = value;
  }

  @Input()
  get readonly(): boolean {
    return this._readonly;
  }

  set readonly(value: boolean) {
    this._readonly = value;
  }

  @Input() placeMark: string;

  @Output()
  textChange: EventEmitter<string> = new EventEmitter();

  @Input()
  set text(value: string) {
    this._text = value;
  }

  get text(): string {
    return this._text;
  }




  get textLength() {
    return this.text.length;
  }
  @ViewChild('stream') stream;
  constructor() {
  }

  onChange($event) {
    this._value$.next($event);
  }

  ngAfterContentInit() {
    const stream$ = this._value$
      .debounceTime(500)
      .distinctUntilChanged()
      .map((value) => (this.textLength === value.length) && (typeof value === 'string') && value)

    stream$.subscribe(input => {
      this.textChange.emit(input);
    });
  }

  /**
   * 如果是 readonly 状态则 取消时间的往下捕捉
   * @param e
   */
  touch(e) {
    if (this.readonly) {
      e.preventDefault();
    }
  }
}
